package com.ph.irp.base.usermanage.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.ph.irp.base.usermanage.service.UserManageService;
import com.ph.irp.base.verifyproject.service.PBaseVerifyprojectCandiateService;
import com.ph.irp.dto.CandiateDTO;
import com.ph.irp.dto.FunctionDTO;
import com.ph.irp.dto.PageDTO;
import com.ph.irp.model.PBasePurviewRole;
import com.ph.irp.model.PBasePurviewUser;
import com.ph.util.StringUtil;
import com.ph.util.pagination.PageUtil;
import com.ph.util.pagination.ShowPageList;
import com.ph.util.report.GenerateFunctionTypePurview;
import com.ph.util.report.GenerateReport;
import com.ph.util.report.GenerateUserGroupPurview;

public class UserManageAction extends ActionSupport implements ShowPageList {
	private HttpSession session;
	private String FORWARD = null;
	private HttpServletRequest request;
	private String username;
	private String userdesc;
	private String password;
	private List<PBasePurviewUser> userList;
	private List<PBasePurviewRole> userGroupList;
	private List<PBasePurviewUser> tempUserList;
//	private List<PBasePurviewRole> tempUserGroupList;
	private List<CandiateDTO> candiateList;
//	private PageDTO userPage;
//	private String cUserPage;
//	private PageDTO userGroupPage;
//	private String cUserGroupPage;
	
	private PageDTO page;
	private String cpage;
	private String rolename;
	private String roledesc;
	private String roleId;
	private String functionTypeId;
	private String candiateId;
	private CandiateDTO candiateDTO;

	private PBasePurviewUser editedUser;
	private PBasePurviewRole editedUserRole;

	private String[] leftUser;

	private String[] rightUser;
	private String groupName;
	private String moduleName;
	private String downloadChineseFileName;

	private UserManageService userManageService;
	private PBaseVerifyprojectCandiateService candiateService;

	// 下载文件原始存放路径
	private final static String DOWNLOADFILEPATH = "/download/";

	public PageDTO getPage() {
		return page;
	}

	public void setPage(PageDTO page) {
		this.page = page;
	}

	public String getCpage() {
		return cpage;
	}

	public void setCpage(String cpage) {
		this.cpage = cpage;
	}

	public String getFunctionTypeId() {
		return functionTypeId;
	}

	public void setFunctionTypeId(String functionTypeId) {
		this.functionTypeId = functionTypeId;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String[] getLeftUser() {
		return leftUser;
	}

	public void setLeftUser(String[] leftUser) {
		this.leftUser = leftUser;
	}

	public String[] getRightUser() {
		return rightUser;
	}

	public void setRightUser(String[] rightUser) {
		this.rightUser = rightUser;
	}

	public PBasePurviewUser getEditedUser() {
		return editedUser;
	}

	public void setEditedUser(PBasePurviewUser editedUser) {
		this.editedUser = editedUser;
	}

	public PBasePurviewRole getEditedUserRole() {
		return editedUserRole;
	}

	public void setEditedUserRole(PBasePurviewRole editedUserRole) {
		this.editedUserRole = editedUserRole;
	}

	public String getRolename() {
		return rolename;
	}

	public void setRolename(String rolename) {
		this.rolename = rolename;
	}

	public String getRoledesc() {
		return roledesc;
	}

	public void setRoledesc(String roledesc) {
		this.roledesc = roledesc;
	}

	public void setUserManageService(UserManageService userManageService) {
		this.userManageService = userManageService;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUserdesc() {
		return userdesc;
	}

	public void setUserdesc(String userdesc) {
		this.userdesc = userdesc;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public List<PBasePurviewUser> getUserList() {
		return userList;
	}

	public void setUserList(List<PBasePurviewUser> userList) {
		this.userList = userList;
	}

	public List<PBasePurviewRole> getUserGroupList() {
		return userGroupList;
	}

	public void setUserGroupList(List<PBasePurviewRole> userGroupList) {
		this.userGroupList = userGroupList;
	}

	public String addUser() throws Throwable {
		PBasePurviewUser user = new PBasePurviewUser();

		user.setPassword(getPassword());
		user.setUserDesc(getUserdesc());
		user.setUserName(getUsername());
		user.setPBaseVerifyprojectCandiateId(Integer.parseInt(candiateId));

		userManageService.addUser(user);
		FORWARD = "success";

		return FORWARD;
	}

	public String editUser() throws Throwable {
		editedUser.setPBaseVerifyprojectCandiateId(candiateDTO.getCandiate()
				.getCandiateId());
		userManageService.editUser(editedUser);
		FORWARD = "success";

		return FORWARD;
	}

	public String addUserGroup() throws Throwable {
		PBasePurviewRole role = new PBasePurviewRole();

		role.setRoleDesc(roledesc);
		role.setRoleName(rolename);

		userManageService.addUserGroup(role);

		int roleID = userManageService.getRoleIdByRoleNameAndDesc(rolename,
				roledesc);
		userManageService.addUserRole(leftUser, roleID);

		FORWARD = "success";

		return FORWARD;
	}

	public String editUserGroup() throws Throwable {

		userManageService.editUserRole(editedUserRole);

		userManageService.deleteUserRole(editedUserRole.getRoleId());
		userManageService.addUserRole(leftUser, editedUserRole.getRoleId());
		FORWARD = "success";

		return FORWARD;
	}

	public String deleteUserAndRole() throws Throwable {
		request = ServletActionContext.getRequest();
		session = ServletActionContext.getRequest().getSession();
		String deletedUserID = (String) request.getParameter("deletedUserID");
		String deletedRoleID = (String) request.getParameter("deletedRoleID");

		if (deletedUserID != null && !deletedUserID.equals("")) {
			userManageService.deleteUser(StringUtil
					.removeLastComma(deletedUserID));
		}
		if (deletedRoleID != null && !deletedRoleID.equals("")) {
			userManageService.deleteUserGroup(StringUtil
					.removeLastComma(deletedRoleID));
		}

		FORWARD = "success";

		return FORWARD;
	}

	public String showAddUserGroup() throws Throwable {
		request = ServletActionContext.getRequest();

		ArrayList<PBasePurviewUser> leftList = new ArrayList<PBasePurviewUser>();
		List<PBasePurviewUser> rightList = userManageService.getAllUser();

		request.setAttribute("rightList", rightList);
		request.setAttribute("leftList", leftList);
		FORWARD = "success";

		return FORWARD;
	}

	public String showEditUserPurview() throws Throwable {
		request = ServletActionContext.getRequest();
		String editUserGroupID = (String) request
				.getParameter("editUserGroupID");

		editedUserRole = userManageService.getRoleByRoleId(editUserGroupID);
		List<Integer> functionIDOfRoleIDs = userManageService
				.getFunctionByRoleID(editUserGroupID);

		Map functionTypeMap = userManageService.getFunctionType();

		if (functionIDOfRoleIDs != null && editedUserRole != null
				&& functionTypeMap != null) {
			request.setAttribute("functionTypeMap", functionTypeMap);
			request.setAttribute("editedUserRole", editedUserRole);
			request.setAttribute("functionIDOfRoleIDs", functionIDOfRoleIDs);
			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	public String editUserPurview() throws Throwable {
		request = ServletActionContext.getRequest();
		String editFunctionTypeID = (String) request
				.getParameter("editFunctionTypeID");

		String editUserGroupID = (String) request
				.getParameter("editUserGroupID");

		userManageService.editUserPurview(editFunctionTypeID, editUserGroupID);
		FORWARD = "success";

		return FORWARD;
	}

	public String showEditUserGroup() throws Throwable {
		request = ServletActionContext.getRequest();
		session = ServletActionContext.getRequest().getSession();

		int userID = (Integer) session.getAttribute("userId");
		String editUserGroupID = (String) request
				.getParameter("editUserGroupID");

		editedUserRole = userManageService.getRoleByRoleId(editUserGroupID);

		if (editedUserRole != null) {
			List<PBasePurviewUser> leftList = userManageService
					.getUserRoleByRoleId(editUserGroupID, userID);
			List<PBasePurviewUser> rightList = userManageService
					.getUserRoleNotByRoleId(editUserGroupID, userID);

			request.setAttribute("rightList", rightList);
			request.setAttribute("leftList", leftList);
			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	public String showEditUser() throws Throwable {
		request = ServletActionContext.getRequest();
		String editUserId = (String) request.getParameter("editUserID");
		editedUser = userManageService.getUserByUserId(editUserId);

		if (editedUser != null) {
			candiateDTO = candiateService.getCandiateById(editedUser
					.getPBaseVerifyprojectCandiateId());
			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	public String getUserAndRole() throws Throwable {
		request = ServletActionContext.getRequest();
		session = ServletActionContext.getRequest().getSession();

		int userID = (Integer) session.getAttribute("userId");
		userList = userManageService.getUserListByUserNameExcludeCurrentUserID(
				username, userID);
		userGroupList = userManageService.getUserGroupListByRoleName(rolename);
		if (userList != null && userGroupList != null) {
			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	public String showUserList() throws Throwable {
		request = ServletActionContext.getRequest();
		session = ServletActionContext.getRequest().getSession();

		int userID = (Integer) session.getAttribute("userId");
		tempUserList = userManageService.getAllUserExcludeCurrentUserID(userID);
		userGroupList = userManageService.getAllUserGroup();

		if (tempUserList != null && userGroupList != null) {
			if (tempUserList.size() != 0) {
				cpage = "1";
				page = PageUtil.generatePageDTO(tempUserList,
						"showUserManagePageList.action", cpage);
				userList = page.getResList();
			} else {
				userList = tempUserList;
			}

			
			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	public String showPageList() throws Throwable {
		if (tempUserList != null) {
			page = PageUtil.generatePageDTO(tempUserList,
					"showUserManagePageList.action", cpage);
			userList = page.getResList();

			FORWARD = "success";
		} else {
			FORWARD = "input";
		}
		return FORWARD;
	}

	public String showPurviewView() throws Throwable {
		request = ServletActionContext.getRequest();
		List<PBasePurviewRole> groupList = userManageService.getAllUserGroup();
		Map functionTypeMap = userManageService.getFunctionType();

		if (groupList != null && functionTypeMap != null) {
			request.setAttribute("functionTypeMap", functionTypeMap);
			request.setAttribute("groupList", groupList);

			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	public String viewByUserGroup() throws Throwable {
		request = ServletActionContext.getRequest();
		List<FunctionDTO> functionList = null;
		String groupName = null;
		if (!roleId.equals("0")) {
			functionList = userManageService.getFunctionTypeByGroupID(roleId);
			groupName = userManageService.getRoleByRoleId(roleId).getRoleName();
		} else {
			functionList = userManageService.getAllFunctionType();
			groupName = "所有用户组";
		}

		if (functionList != null) {
			request.setAttribute("functionList", functionList);
			request.setAttribute("groupName", groupName);
			request.setAttribute("roleId", roleId);
			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	public String viewByFunctionType() throws Throwable {
		request = ServletActionContext.getRequest();
		List<FunctionDTO> functionList = null;
		String moduleName = null;
		if (!functionTypeId.equals("0")) {
			functionList = userManageService
					.getFunctionTypeByFunctionTypeID(functionTypeId);
			moduleName = userManageService
					.getFunctionTypeNameByFunctionTypeID(functionTypeId);
		} else {
			functionList = userManageService
					.getAllFunctionTypeByFunctionTypeID();
			moduleName = "所有业务组";
		}

		if (functionList != null) {
			request.setAttribute("functionList", functionList);
			request.setAttribute("moduleName", moduleName);
			request.setAttribute("functionTypeId", functionTypeId);
			FORWARD = "success";
		} else {
			FORWARD = "input";
		}

		return FORWARD;
	}

	// 从下载文件原始存放路径读取得到文件输出流
	public InputStream getExcelFile() throws Throwable {
		request = ServletActionContext.getRequest();
		functionTypeId = (String) request.getParameter("functionTypeId");
		roleId = (String) request.getParameter("roleId");
		groupName = (String) request.getParameter("groupName");
		moduleName = (String) request.getParameter("moduleName");

		HSSFSheet sheet = null;
		HSSFWorkbook workbook = new HSSFWorkbook();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {
			if (groupName != null && !groupName.equals("")) {
				sheet = workbook.createSheet(setEncoding(groupName) + "权限浏览");
			} else if (moduleName != null && !moduleName.equals("")) {
				sheet = workbook.createSheet(setEncoding(moduleName) + "权限浏览");
			}

			List<FunctionDTO> functionList = new ArrayList<FunctionDTO>();
			if (functionTypeId != null) {
				GenerateReport gr = new GenerateFunctionTypePurview();
				gr.createSheetHead(sheet);
				if (!functionTypeId.equals("0")) {
					functionList = userManageService
							.getFunctionTypeByFunctionTypeID(functionTypeId);

				} else {
					functionList = userManageService
							.getAllFunctionTypeByFunctionTypeID();

				}

				gr.createSheetContent(sheet, functionList);
			} else if (roleId != null) {
				GenerateReport gr = new GenerateUserGroupPurview();
				gr.createSheetHead(sheet);
				if (!roleId.equals("0")) {
					functionList = userManageService
							.getFunctionTypeByGroupID(roleId);

				} else {
					functionList = userManageService.getAllFunctionType();

				}

				gr.createSheetContent(sheet, functionList);
			}

			workbook.write(baos);// 写入
		} catch (IOException e) {
			e.printStackTrace();
		}

		byte[] ba = baos.toByteArray();
		ByteArrayInputStream bais = new ByteArrayInputStream(ba);
		return bais;
	}

	private String setEncoding(String name) throws UnsupportedEncodingException {
		return new String(name.getBytes("ISO-8859-1"), "UTF-8");
	}

	private String setURLEncoding(String name)
			throws UnsupportedEncodingException {
		return URLEncoder.encode(name, "ISO-8859-1");
	}

	// 如果下载文件名为中文，进行字符编码转换
	public String getDownloadChineseFileName() {
		request = ServletActionContext.getRequest();

		groupName = (String) request.getParameter("groupName");
		moduleName = (String) request.getParameter("moduleName");

		try {

			if (groupName != null && !groupName.equals("")) {
				downloadChineseFileName = new String(setURLEncoding(groupName)
						.getBytes(), "ISO-8859-1");
			} else if (moduleName != null && !moduleName.equals("")) {
				downloadChineseFileName = new String(setURLEncoding(moduleName)
						.getBytes(), "ISO-8859-1");
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return downloadChineseFileName;
	}

	public String downloadPurviewView() {
		return SUCCESS;
	}

	public void setCandiateService(
			PBaseVerifyprojectCandiateService candiateService) {
		this.candiateService = candiateService;
	}

	public String getCandiateId() {
		return candiateId;
	}

	public void setCandiateId(String candiateId) {
		this.candiateId = candiateId;
	}

	public CandiateDTO getCandiateDTO() {
		return candiateDTO;
	}

	public void setCandiateDTO(CandiateDTO candiateDTO) {
		this.candiateDTO = candiateDTO;
	}

}
